import {queryList, queryOne, update} from "@/utils/db";

export interface Blog {
    id?: number,
    title: string,
    summary: string,
    image: string,
    content: string,
    createTime: Date,
    updateTime?: Date,
    author: string,
}

export async function getBlogList(page: number, pageSize: number) {
    let start = (page - 1) * pageSize
    return await queryList(`select *
                            from blog
                            order by createTime desc
                            limit ?,?`, [start, pageSize])
}

export async function getBlogCount() {
    let res = await queryOne(`select count(*) as count
                              from blog`)
    return res.count
}

export async function getBlogById(id: number) {
    return await queryOne(`select *
                           from blog
                           where id = ?`, [id])
}

export async function getBlogComments(id: number) {
    return await queryList("select * from `blog-comment` where blogId = ? order by createTime desc", [id])
}

export async function addBlogComment(blogId: number, content: string, author: string) {
    let date = new Date()
    const res = await update("insert into `blog-comment` (blogId, content, author, createTime) values (?, ?, ?, ?)", [blogId, content, author, date])
    return {blogId, content, author, createTime: date, id: res.insertId}
}

export async function editBlog(blog: Blog) {
    blog.updateTime = new Date()
    const res = await update("update blog set title = ?, summary= ?, content = ? , image = ?, author=?, createTime=?, updateTime=? where  id = ?", [blog.title, blog.summary, blog.content, blog.image, blog.author, blog.createTime, blog.updateTime, blog.id])
    return blog
}

export async function addBlog(blog: Blog) {
    blog.updateTime = undefined
    blog.createTime = new Date()
    const res = await update("insert into blog (title, summary, image, content, author, createTime) values (?,?,?,?,?,?)", [blog.title, blog.summary, blog.image, blog.content, blog.author, blog.createTime])
    return blog.id = res.insertId
}